<?php

namespace api\controllers;

use common\models\Order;
use common\models\Shop;
use common\models\Complaint;
use common\models\ComplaintImg;
use common\models\Active;
use common\models\ActiveAttr;
use common\models\CountComplaint;
use yii\web\Controller;
use common\service\QiniuService;
use common\service\GlobalUrlService;
use common\service\ConstantService;
use common\service\WechatService;
use common\service\GoodsService;
class ComplaintController extends BaseController
{

    /**
     * 上传图片
     */
    public function actionAddimg(){
        $type = '.'.strtolower(substr(strrchr($_FILES['file']['name'],"."),1));
        $result = QiniuService::uploadFile($_FILES['file']['tmp_name'],$type);
        if($result){
            return $this->renderJson(['url'=>$result,'cdn'=>GlobalUrlService::buildCdnUrl('')],'',ConstantService::$response_fail);
        }
        return $this->renderJson([],'上传失败',ConstantService::$response_fail);
    }

    /**
     * 添加收货申请
     */
    public function actionAdd(){
        $data = $this->post();

        $msg = $this->_validate($data);
        if($msg !== true){
            return $this->renderJson([],$msg,ConstantService::$response_fail);
        }
        $coms = Complaint::findOne(['user_id'=>$this->user['id'],'order_id'=>$data['order_id']]);
        if($coms){
            return $this->renderJson([],'该订单已经申请过售后!',ConstantService::$response_fail);
        }
        $order = Order::findOne(['id'=>$data['order_id']]);

        $data['shop_id'] = $order['shop_id'];
        $data['status'] = 0;
        $data['user_id'] = $this->user['id'];
        $data['create_time'] = time();
        $data['update_time'] = time();

        $ComplaintDb = new Complaint();
        $ComplaintDb->setAttributes($data);

        if($ComplaintDb->save()){
            $id = $ComplaintDb->attributes['id'];
            $arrimg = explode(',',$data['imgs']);
            $this->_saveimage($id,$arrimg);
            $order = Order::findOne(['id'=>$data['order_id']]);
            $order->is_apply_after_sale = 1;
            $order->save();
            //添加售后统计记录
            $re = $this->_addcount($data['sale_type']);
            if($re === false){
                return $this->renderJson([],'保存售后统计记录出错',ConstantService::$response_fail);
            }
            return $this->renderJson($id,'申请售后成功!',ConstantService::$response_success);
        }
        return $this->renderJson([],'申请售后失败!',ConstantService::$response_fail);
    }

    /**
     * @param $sale_type
     * @return bool
     */
    private function _addcount($sale_type){
        $time = strtotime(date('Y-m-d'));
        $row = CountComplaint::findOne(['day'=>date('Y-m-d')]);
        $return_money_num = 0;
        $return_goods_num = 0;
        $other_num = 0;
        if($sale_type == '退款'){
            $return_money_num = 1;
        }elseif($sale_type == '退货'){
            $return_goods_num = 1;
        }elseif($sale_type == '其他'){
            $other_num = 1;

        }
        if($row){
            //修改申请数
            $row->return_money_num = $row['return_money_num'] + $return_money_num;
            $row->return_goods_num = $row['return_goods_num'] + $return_goods_num;
            $row->other_num = $row['other_num'] + $other_num;
            $row->complaint_num = $row['complaint_num'] + 1;
            $row->wait_handle_num = $row['wait_handle_num'] + 1;
            $row->update_time = time();
            $re = $row->save();
        }else{
            //新增一条记录
            $count_data['time'] = $time;
            $count_data['day'] = date('Y-m-d');
            $count_data['complaint_num'] = 1;
            $count_data['return_goods_num'] = $return_goods_num;
            $count_data['return_money_num'] = $return_money_num;
            $count_data['other_num'] = $other_num;
            $count_data['wait_handle_num'] = 1;
            $count_data['pass_num'] = 0;
            $count_data['fail_num'] = 0;
            $count_data['completion_num'] = 0;
            $count_data['create_time'] = time();
            $count_data['update_time'] = time();
            $count_complaint_query = new CountComplaint();
            $count_complaint_query->setAttributes($count_data);
            $re = $count_complaint_query->save();
        }
        if($re){
            return true;
        }
        return false;
    }

    /**
     * 自定义验证
     * @param $data
     * @return bool|string
     */
    private function _validate($data){
        if(empty($data['sale_type'])){
            return '售后类型不能为空';
        }
        if(empty($data['goods_type'])){
            return '货物状态不能为空';
        }
        if(empty($data['reason'])){
            return '申请原因不能为空';
        }
        if(empty($data['problem_description'])){
            return '问题描述不能为空';
        }
        if(empty($data['user_phone'])){
            return '用户联系方式不能为空';
        }
        if(empty($data['user_name'])){
            return '用户姓名不能为空';
        }
        if(empty($data['order_id'])){
            return '订单id不能为空';
        }
        return true;

    }

    /**
     * 保存图片
     * @param $id
     * @param $img_arr
     * @return bool
     * @throws \yii\db\Exception
     */
    private function _saveimage($id,$img_arr){
        if(empty($id) || empty($img_arr)){
            return true;
        }
        $newimg = [];
        foreach ($img_arr as $img){
            $imgdata = [];
            $imgdata['complaint_id'] = $id;
            $imgdata['image'] = $img;
            $newimg[] = $imgdata;
        }
        ComplaintImg::getDb()->createCommand()->batchInsert('complaint_img',['complaint_id','image'],$newimg)->execute();


    }

    /**
     *获取售后列表
     */
    public function actionGetSaleLists(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $page = intval($this->get('page'));
            $page = ( $page > 0 )? $page : 1;
            $condition = ['user_id'=>$user_id];
            $offset = ($page - 1) * $this->page_size;
            $lists = Complaint::find()
                ->where($condition)
                ->orderBy(['create_time' => SORT_DESC])
                ->offset($offset)
                ->limit($this->page_size)
                ->asArray()
                ->all();

            if(!empty($lists)){
                $order_id = array_column($lists,'order_id');
                $shop_id = array_column($lists,'shop_id');
                $order = Order::find()->where(['id' => $order_id])->asArray()->all();


                $active_id = array_column($order,'active_id');
                $new_actives = [];
                if(!empty($active_id)){
                    $actives = Active::find()
                        ->select(['active_name','id as active_id'])
                        ->where(['id'=>$active_id])
                        ->asArray()
                        ->all();
                    foreach ($actives as $value){
                        $lenth = mb_strlen($value['active_name']);
                        if($lenth > 26){
                            $value['active_name'] = mb_substr($value['active_name'],0,26).'...';
                        }
                        $new_actives[$value['active_id']] = $value;
                    }
                    unset($value);
                }
                $shopdata = [];
                if(!empty($shop_id)){
                    $shop = Shop::find()
                        ->select('id,shop_name,shop_logo')
                        ->where(['id'=>$shop_id])
                        ->asArray()
                        ->all();
                    foreach ($shop as $val){
                        $val['shop_logo'] = GlobalUrlService::buildCdnUrl($val['shop_logo']);
                        $shopdata[$val['id']] = $val;
                    }
                    unset($val);
                }
                $goods_attrs_ids = array_column($order,'goods_attr_id');
                $new_goods_attr = [];
                $goods_attrs = ActiveAttr::find()
                    ->select(['attr_img','id'])
                    ->where(['id'=>$goods_attrs_ids])
                    ->asArray()
                    ->all();

                foreach ($goods_attrs as $goods_attr){
                    $new_goods_attr[$goods_attr['id']] = $goods_attr['attr_img'];
                }
                unset($goods_attr);
                //获取属性值
                $attributes = GoodsService::getCurrentArrt($goods_attrs_ids);


                $new_order = [];
                foreach ($order as $item){
                    $item['goods_attr'] = '';
                    if(isset($new_goods_attr[$item['goods_attr_id']]) && !empty($new_goods_attr[$item['goods_attr_id']])){
                        $item['goods_attr_img'] = GlobalUrlService::buildCdnUrl($new_goods_attr[$item['goods_attr_id']]);
                    }
                    $item['active_name'] = '';
                    if(isset($new_actives[$item['active_id']]) && !empty($new_actives[$item['active_id']])){
                        $item['active_name'] = $new_actives[$item['active_id']]['active_name'];
                    }
                    //sku
                    $item['sku'] = '';
                    if(isset($attributes[$item['goods_attr_id']]) && !empty($attributes[$item['goods_attr_id']])){
                        $item['sku'] = $attributes[$item['goods_attr_id']];
                    }
                    $new_order[$item['id']] = $item;
                }
                unset($item);
                foreach ($lists as &$list){
                    $list['order'] = '';
                    if(isset($new_order[$list['order_id']]) && !empty($new_order[$list['order_id']])){
                        $list['order'] = $new_order[$list['order_id']];
                    }
                    $list['shop'] = $shopdata[$list['shop_id']];
                }
                unset($list);
            }
            return $this->renderJson($lists,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 获取申请详情
     */
    public function actionApplyDetailSale(){
        if($this->isGet()){
            $sale_id = $this->get('id');
            $row = Complaint::find()->where(['id'=>$sale_id])->asArray()->one();
            $order = Order::find()->where(['id'=>$row['order_id']])->asArray()->one();
            $active = Active::find()->where(['id'=>$order['active_id']])->asArray()->one();

            $row['order_no'] = $order['order_no'];
            $row['active_name'] = $active['active_name'];
            $lenth = mb_strlen($active['active_name']);
            if($lenth > 26){
                $row['active_name'] = mb_substr($active['active_name'],0,26).'...';
            }

            $row['goods_img'] = GlobalUrlService::buildCdnUrl($active['goods_img']);
            $row['goods_price'] = $order['goods_price'];
            $row['order_money'] = $order['order_money'];
            $row['freight'] = $order['freight'];
            $row['goods_num'] = $order['goods_num'];
            $arrt_val = GoodsService::getCurrentArrt($order['goods_attr_id']);
            if(isset($arrt_val) && !empty($arrt_val)){
                $row['attr_val'] = array_values($arrt_val);
            }

            $shop = Shop::find()
                ->select('id,shop_name,shop_logo')
                ->where(['id'=>$row['shop_id']])
                ->asArray()
                ->one();
            $shop['shop_logo'] = GlobalUrlService::buildCdnUrl($shop['shop_logo']);
            $row['shop'] = $shop;
            return $this->renderJson($row,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    /**
     * 获取沟通详情
     */
    public function actionGetDetailSale(){
        if($this->isGet()){
            $sale_id = $this->get('id');
            $row = Complaint::find()->where(['id'=>$sale_id])->asArray()->one();
            $row['user_logo'] = GlobalUrlService::buildCdnUrl($this->user['avatarurl']);
            $shop = Shop::findOne(['id'=>$row['shop_id']]);
            $row['shop_logo'] = GlobalUrlService::buildCdnUrl($shop['shop_logo']);
            return $this->renderJson($row,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }
}